<template>
  <t-dialog
    :visible="visible"
    :header="dialogTitle"
    width="600px"
		top="5vh"
    @confirm="handleSubmit"
    @cancel="handleCancel"
    :confirm-btn="{ loading: submitLoading }"
		@close="handleCancel"
  >
    <t-form
      ref="catalogForm"
      :data="formData"
      :rules="formRules"
      label-align="left"
      label-width="100px"
      class="catalog-form"
    >
      <!-- 父级节点显示 -->
      <t-form-item label="父级节点">
        <div class="parent-node-display">
          <t-icon name="folder" class="folder-icon" />
          <span class="parent-name">{{ parentNodeName }}</span>
        </div>
      </t-form-item>

      <!-- 目录编码 -->
      <t-form-item label="目录编码" name="code">
        <t-input
          v-model="formData.code"
          placeholder="请输入目录编码"
          maxlength="50"
          :disabled="isEdit"
        />
        <div class="form-tip">目录编码用于系统内部标识，创建后不可修改</div>
      </t-form-item>

      <!-- 目录名称 -->
      <t-form-item label="目录名称" name="name">
        <t-input
          v-model="formData.name"
          placeholder="请输入目录名称"
          maxlength="100"
        />
      </t-form-item>

      <!-- 推送开始时间 -->
      <t-form-item label="推送开始时间" name="pushStartTime">
        <t-date-picker
          v-model="formData.pushStartTime"
          placeholder="请选择推送开始时间"
          format="YYYY-MM-DD HH:mm:ss"
          enable-time-picker
          style="width: 100%"
        />
      </t-form-item>

      <!-- 推送结束时间 -->
      <t-form-item label="推送结束时间" name="pushEndTime">
        <t-date-picker
          v-model="formData.pushEndTime"
          placeholder="请选择推送结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          enable-time-picker
          style="width: 100%"
        />
      </t-form-item>

      <!-- 描述 -->
      <t-form-item label="描述" name="description">
        <t-textarea
          v-model="formData.description"
          placeholder="请输入目录描述（可选）"
          :maxlength="500"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script>
import { addCatalogNode, updateCatalogNode } from '@/api/catalog';

export default {
  name: 'CatalogForm',
  model: {
    prop: 'visible',
    event: 'update:visible',
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 当前编辑的节点数据（有 id 表示编辑，无 id 表示新增）
    nodeData: {
      type: Object,
      default: () => ({}),
    },
    // 父节点数据
    parentNode: {
      type: Object,
      default: null,
    },
    // 疾病分类ID
    categoryId: {
      type: [String, Number],
      required: true,
			default: null,
    },
  },
  emits: ['update:visible', 'success'],
  data() {
    return {
      submitLoading: false,
      formData: {
        code: '',
        name: '',
        pushStartTime: '',
        pushEndTime: '',
        description: '',
      },
      formRules: {
        code: [
          { required: true, message: '请输入目录编码', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9_-]+$/,
            message: '目录编码只能包含字母、数字、下划线和横线',
            trigger: 'blur'
          },
          { max: 50, message: '目录编码不能超过50个字符', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          { max: 100, message: '目录名称不能超过100个字符', trigger: 'blur' },
        ],
        pushEndTime: [
          {
            validator: (val) => {
              if (val && this.formData.pushStartTime) {
                return new Date(val) > new Date(this.formData.pushStartTime);
              }
              return true;
            },
            message: '推送结束时间必须晚于开始时间',
            trigger: 'change',
          },
        ],
      },
    };
  },
  computed: {
    // 通过是否有 id 来判断是编辑还是新增
    isEdit() {
      return !!(this.nodeData && this.nodeData.id);
    },
    dialogTitle() {
      return this.isEdit ? '编辑目录' : '添加目录';
    },
    parentNodeName() {
      if (this.parentNode) {
        return this.parentNode.data?.name || this.parentNode.name || '未知节点';
      }
      return '根节点';
    },
    parentId() {
      return this.parentNode?.data?.id || this.parentNode?.id || null;
    },
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          this.initFormData();
        } else {
          this.resetForm();
        }
      },
      immediate: true,
    },
    nodeData: {
      handler() {
        if (this.visible) {
          this.initFormData();
        }
      },
      deep: true,
    },
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      if (this.nodeData) {
        this.formData = {
          code: this.nodeData.code || '',
          name: this.nodeData.name || '',
          pushStartTime: this.nodeData.pushStartTime || '',
          pushEndTime: this.nodeData.pushEndTime || '',
          description: this.nodeData.description || '',
        };
      } else {
        this.resetForm();
      }
    },

    // 重置表单
    resetForm() {
      this.formData = {
        code: '',
        name: '',
        pushStartTime: '',
        pushEndTime: '',
        description: '',
      };
      this.$nextTick(() => {
        this.$refs.catalogForm?.clearValidate();
      });
    },

    // 提交表单
    async handleSubmit() {
      try {
        const valid = await this.$refs.catalogForm.validate();

				if (valid !== true) {
					return;
				}

        this.submitLoading = true;

        const submitData = {
          code: this.formData.code,
          name: this.formData.name,
          pushStartTime: this.formData.pushStartTime,
          pushEndTime: this.formData.pushEndTime,
          description: this.formData.description,
        };

        let res;
        if (this.isEdit) {
          // 编辑操作 - 只传递需要更新的字段和节点ID
          submitData.id = this.nodeData.id;
          res = await updateCatalogNode(submitData);
        } else {
          // 新增操作 - 需要传递categoryId和parentId
          submitData.categoryId = this.categoryId;
          submitData.parentId = this.parentId;
          res = await addCatalogNode(submitData, this.parentId);
        }

        if (res?.data?.code === 200) {
          this.$message.success(this.isEdit ? '编辑成功' : '添加成功');
          this.$emit('success');
          this.handleCancel();
        } else {
          throw new Error(res?.data?.message || '操作失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        if (error.message) {
          this.$message.error(error.message);
        }
      } finally {
        this.submitLoading = false;
      }
    },

    // 取消操作
    handleCancel() {
      this.$emit('update:visible', false);
    },
  },
};
</script>

<style lang="less" scoped>
.catalog-form {
  .parent-node-display {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: #f8f9fa;
    border: 1px solid #e7e7e7;
    border-radius: 4px;
    color: #666;

    .folder-icon {
      margin-right: 8px;
      color: #1890ff;
    }

    .parent-name {
      font-weight: 500;
    }
  }

  .form-tip {
    margin-top: 4px;
    font-size: 12px;
    color: #999;
    line-height: 1.4;
  }
}

:deep(.t-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.t-dialog__body) {
  padding: 24px;
}
</style>